package com.xjnt.frameworks.core;

import java.sql.Timestamp;

import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.Table;
import com.jfinal.plugin.activerecord.TableMapping;
import com.xjnt.frameworks.utils.UUIDKit;

/**
 * Model 抽象类
 * 
 * @author caoyong
 *
 * @param <M>
 */
public abstract class BaseModel<M extends BaseModel<M>> extends Model<M> {
	/**
	 * @serialField
	 */
	private static final long serialVersionUID = 1L;
	
	private Table table;
	private String tableName;
	private String[] primaryKey;
	private String modelName;

	@Override
	public boolean save() {
		this.set(getPrimaryKey()[0], UUIDKit.base58Uuid());
		return super.save();
	}
	
	@Override
	public boolean update() {
		if(getTable().hasColumnLabel("update_time")){
			this.set("update_time", new Timestamp(System.currentTimeMillis()));
		}
		return super.update();
	}
	
	/**
	 * 获取表对象
	 * 
	 * @return
	 */
	public Table getTable() {
		if (table == null) {
			table = TableMapping.me().getTable(getClass());
		}
		return table;
	}

	/**
	 * 数据库表名
	 * 
	 * @return
	 */
	public String getTableName() {
		if (tableName == null) {
			tableName = getTable().getName();
		}
		return tableName;
	}

	/**
	 * 主键
	 * 
	 * @return
	 */
	public String[] getPrimaryKey() {
		if (primaryKey == null) {
			primaryKey = getTable().getPrimaryKey();
		}
		return primaryKey;
	}

	public String getModelName() {
		if (modelName == null) {
			modelName = StrKit.firstCharToLowerCase(getClass().getSimpleName());
		}
		return modelName;
	}
}
